import { fetchCart } from '@/control/core/api';

export default ( Vue ) => Vue.mixin( {
  methods: {
    // todo: 返回用户的 userID
    getUserID() {
      const user = JSON.parse( window.sessionStorage.getItem( 'user' ) );
      return user && user.userID;
    },

    // todo: 返回订单号
    getOrderID() {
      return this.$store.getters['pubStore/getPayOrder'].orderID;
    },

    // todo: 返回当前用户角色ID。100 ~ 199：店员；200 以上为会员
    getUserRoleID() {
      const user = JSON.parse( window.sessionStorage.getItem( 'user' ) );
      return user.role.roleID;
    },

    // todo: 返回用户名
    getUserName() {
      const user = JSON.parse( window.sessionStorage.getItem( 'user' ) );
      return user && ( user.name || user.mobile );
    },

    // todo: 返回用户头像
    getUserHeader() {
      const user = JSON.parse( window.sessionStorage.getItem( 'user' ) );
      return user && ( user.pic1 || user.pic2 );
    },

    // todo: 设置页面右上角中购物车数量
    async fetchCart( id ) {
      const roleID = this.getUserRoleID();
      const data = await fetchCart( id );
      let type = roleID < 200 ? 'staffStore' : 'pubStore';
      let getNum = function ( arr ) {
        var nums = 0;
        arr.forEach( function ( v ) {
          nums += v.num;
        } );
        return nums;
      };

      this.$store.dispatch( `${type}/changeCartNum`, {
        num: getNum( data.result )
      } );

      this.$store.dispatch( `${type}/changeCartItems`, data.result );
      return data;
    }
  }
} );
